# coding: utf-8
"""
-------------------------------------------------
   File Name：    MongodbClient.py
   Description :  封装mongodb操作
   Author :       chaoqun.chen
   date：          2017/3/3
-------------------------------------------------
   Change Activity:
                   2017/3/3:
                   2017/9/26:完成对mongodb的支持
-------------------------------------------------
"""
__author__ = 'chaoqun.chen'

from pymongo import MongoClient

class MongodbClient(object):
    def __init__(self, name, host, port, **kwargs):
        self.name = name
        self.client = MongoClient(host, port, **kwargs)
        self.db = self.client.proxy

    def changeTable(self, name):
        self.name = name

    def get(self, proxy_str):
        data = self.db[self.name].find_one({'proxy': proxy_str})
        if data is not None:
            return data['num']
        return None

    def put(self, proxy_obj):
        if self.db[self.name].find_one({'proxy': proxy_obj.proxy}):
            return None
        else:
            self.db[self.name].insert_one(proxy_obj.info_dict)

    def delete(self, proxy_str):
        self.db[self.name].delete_one({'proxy': proxy_str})

    def getAll(self):
        result_list = list()
        for p in self.db[self.name].find({}, {'_id': 0}):
            result_list.append(p)
        return result_list

    def clean(self):
        self.client.drop_database('proxy')

    def delete_all(self):
        self.db[self.name].remove()

    def update(self, proxy_obj):
        self.db[self.name].update({'proxy': proxy_obj.proxy}, proxy_obj.info_dict)

    def exists(self, proxy_str):
        data = self.db[self.name].find_one({'proxy': proxy_str})
        if data is not None:
            return True
        return False

    def getNumber(self):
        return self.db[self.name].estimated_document_count()


if __name__ == "__main__":
    db = MongodbClient('raw_proxy', 'chencq.cn', 27017)
    print(db.getAll())